//
//  EmoticonViewModel.swift
//  表情键盘
//
//  Created by mac on 15/9/17.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class EmoticonViewModel {
  
    ///单例
    static let shareViewModel = EmoticonViewModel()
    /// 表情包的数组
    lazy var packages = [EmoticonPackage]()
    
    private init() {
        //加载表情包
        loadPackages()
    }
    
    ///表情包的数组
    func favorite (indexPth:NSIndexPath){
        //0,如果是第0个分组，不参与排序
        if indexPth.section == 0 {
            return
        }
        //1，获取表情符号
        let em = emoticon(indexPth)
        em.times++
        
        //2,将表情符号添加到第0组的首位
        //判断是否已经存在表情
        if !packages[0].emoticons.contains(em){
            packages[0].emoticons.insert(em, atIndex: 0)
        }
        
        //3，对数组进行排序，直接排序当前数组sortInPlace
        //Swift中，对尾随闭包，同时又返回值的以一个简单写法
//        packages[0].emoticons.sortInPlace { (obj1, obj2) -> Bool in
//            return obj1.times > obj2.times
//        }
        //$0对应的第一个餐宿，$1对应第二个参数，以此类推 return 可以神略
        packages[0].emoticons.sortInPlace{$0.times > $1.times}
        
        //4.删除多余的表情 - 倒数第二个
        if packages[0].emoticons.count > 21{
            packages[0].emoticons.removeAtIndex(20)
        }
    
        // 数组的调试技巧
        printLog(packages[0].emoticons as NSArray)
        printLog(packages[0].emoticons.count)
    }
    /// 添加表情包
   private func loadPackages(){
        
        // 0. 增加最近分组
        packages.append(EmoticonPackage(dict: ["group_name_cn": "最近AA"]))
       
        //1，读取emoticons.plist
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        
        //2，读取字典
        let dict = NSDictionary(contentsOfFile: path!)
        let array = dict!["packages"] as! [[String : AnyObject]]
        
        for infoDict in array{
            //1,获取id，目录中对应的 info.plist 才是表情包的数据
            let id = infoDict["id"] as! String
            
            //2.拼接表情包路径
            let emPath = NSBundle.mainBundle().pathForResource("info.plist", ofType: nil, inDirectory: "Emoticons.bundle/" + id)
            
            //3.加载info.plist 字典
            let packageDict = NSDictionary(contentsOfFile: emPath!) as! [String: AnyObject]
            
            //4.字典转模型
            packages.append(EmoticonPackage(dict: packageDict))
        }
        print(packages)
    }
    /// 根据 indexPath 返回对应的表情模型
    ///
    /// - parameter indexPath: indexPath
    ///
    /// - returns: 表情模型
    func emoticon(indexPath:NSIndexPath) -> Emoticon{
        return packages[indexPath.section].emoticons[indexPath.item]
    }
}
